package com.xoa.controller.financialManage.contract;

import com.xoa.model.financialManage.contract.*;

import com.xoa.model.workflow.FlowRun;
import com.xoa.service.financialManage.contract.ContractManageService;
import com.xoa.util.ExcelUtil;
import com.xoa.util.LimsJson;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jarvishao
 * @site
 * @create 2019-12-13-17:10
 */
@Controller
@RequestMapping("/contract")//我的合同
public class ContractManageController {

    @Autowired
    ContractManageService contractManageService;

    @RequestMapping("/manager")//进合同管理
    public String goContract(){
        return "/app/financialManage/contract/manager";
    }
    @RequestMapping("/mine")//进我的合同
    public String goMine(){
        return "/app/financialManage/contract/mine";
    }
    @RequestMapping("/new")//进新建合同
    public String goNew(){
        return "/app/financialManage/contract/new";
    }

    @RequestMapping("/recycle")//进回收站 ****
    public String goecycle(){
        return "/app/financialManage/contract/recycle";
    }

    @RequestMapping("/type")//进合同类型
    public String goType(){
        return "/app/financialManage/contract/type";
    }
    @RequestMapping("/details")//进合同管理查看详情
    public String goDetails(){
        return "/app/financialManage/contract/details";
    }
    @RequestMapping("/edit")//进新建合同
    public String goEdit(){
        return "/app/financialManage/contract/edit";
    }


    /**
     * 事务提醒，合同提醒
     * @return
     */
    @RequestMapping("/remindFlag")
    public void remindFlag(){
        contractManageService.remindercontract();
    }

    /*
    合同类型crud
     */
    @ResponseBody
    @RequestMapping("/insertType")//增加合同类型
    public ToJson<ContractType> insertType(HttpServletRequest request, ContractType contractType){
        return contractManageService.insertType(request,contractType);
    }
    @ResponseBody
    @RequestMapping("/delType")//删除合同类型
    public ToJson<ContractType> delType(HttpServletRequest request, @RequestParam("ids[]") Integer[] ids){
        return contractManageService.delType(request,ids);
    }
    @ResponseBody
    @RequestMapping("/upType")//更新合同类型
    public ToJson<ContractType> upType(HttpServletRequest request, ContractType contractType){
        return contractManageService.upType(request,contractType);
    }
    @ResponseBody
    @RequestMapping("/selectTypeAll")//查询所有合同类型
    public LimsJson<ContractType> selectTypeAll(HttpServletRequest request, Integer page, Integer limit,Integer pageSize, Map map){
        return contractManageService.selectTypeAll(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectTypeById")//一条合同类型
    public ToJson<ContractType> selectTypeById(HttpServletRequest request,@RequestParam("TypeId") Integer typeId){
        return contractManageService.selectTypeById(request,typeId);
    }
    @ResponseBody
    @RequestMapping("/selectTypeBy")//模糊查询合同类型
    public LimsJson<ContractType> selectTypeBy(HttpServletRequest request,@RequestParam("cha") String cha,Integer page,
                                               Integer limit,Integer pageSize, Map map){
        return contractManageService.selectTypeBy(request,cha,page,limit,pageSize,map);
    }

    /*
    新建合同
    */
    @ResponseBody
    @RequestMapping("/insertContract")//增加合同
    public ToJson<Contract> insertContract(HttpServletRequest request, @RequestBody Contracts contracts){
        return contractManageService.insertContract(request,contracts);
    }

    //更新整个合同
    @ResponseBody
    @RequestMapping("/upContracts")
    public ToJson<Contract> upContracts(HttpServletRequest request,@RequestBody Contracts contracts){
        return contractManageService.upContracts(request,contracts);
    }

    @ResponseBody
    @RequestMapping("/delContract")//删除合同
    public ToJson<Contract> delContract(HttpServletRequest request, @RequestParam("ids[]") Integer[] ids){
        return contractManageService.delContract(request,ids);
    }

    //更新合同
    @ResponseBody
    @RequestMapping("/upContract")
    public ToJson<Contract> upContract(HttpServletRequest request, Contract contract){
        return contractManageService.upContract(request,contract);
    }


    //查询所有合同
    @ResponseBody
    @RequestMapping("/selectContractAll")
    public LimsJson<Contract> selectContractAll(HttpServletRequest request,HttpServletResponse response, Integer page, Integer limit,boolean useFlag,boolean isExport){
        LimsJson<Contract> contractLimsJson = contractManageService.selectContractAll(request, page, limit, useFlag);
        try {
            if (isExport && contractLimsJson.isFlag() && contractLimsJson.getObject() != null){
                List<Contract> contractList = (List<Contract>) contractLimsJson.getData();
                List<Map<String,Object>> contractListMap = new ArrayList<>();
                contractList.forEach(item -> {
                    Map map1 = new HashMap();
                    //序号
                    map1.put("contractId",item.getContractId());
                    //合同编号
                    map1.put("contractNo",item.getContractNo());
                    //项目
                    map1.put("title",item.getTitle());
                    //客户名称
                    map1.put("targetName",item.getTargetName());
                    //签订时间
                    map1.put("dateComment",item.getDateComment());
                    //授权代表
                    map1.put("authorizedRepresentative",item.getAuthorizedRepresentative());
                    //开始
                    map1.put("durationStartdate",item.getCloneDurationStartdate());
                    //终止
                    map1.put("durationEnddate",item.getCloneDurationEnddate());
                    //执行单位
                    map1.put("executiveUnit",item.getExecutive_unit());
                    //合同金额
                    map1.put("money",item.getMoney().toString());
                    //付款方式及比例
                    map1.put("payment",item.getPayment());
                    //合同评审 是
                    map1.put("contractApproval1",item.getContract_approval().equals("1") ? "是" : "" );
                    //合同评审 否
                    map1.put("contractApproval0",item.getContract_approval().equals("0") ? "否" : "");
                    //风险评估 是
                    map1.put("riskAssessment1",item.getRisk_assessment().equals("1") ? "是" : "");
                    //风险评估 否
                    map1.put("riskAssessment0",item.getRisk_assessment().equals("0") ? "否" : "");
                    //备注
                    map1.put("remarks",item.getRemarks());
                    //合同种类
                    map1.put("contractType",!StringUtils.checkNull(item.getContractTypeName()) ? item.getContractTypeName() : "" );
                    contractListMap.add(map1);
                });
                String filename = "局重大合同台账.xls";
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead(filename, 16);
                String[] secondTitles = { "序号" , "合同编号","项目","客户名称","签订时间","授权代表","开始","终止","执行单位","合同金额","付款方式及比例", "是","否", "是","否","备注","合同种类" };
                HSSFSheet sheet = workbook1.getSheetAt(0);
                HSSFRow rowField = sheet.createRow(1);
                HSSFRow rowField2 = sheet.createRow(2);
                HSSFCellStyle styleField = ExcelUtil.createStyle(workbook1, (short)13);
                for (int i = 0; i < secondTitles.length; i++) {
                    HSSFCell cell = rowField.createCell(i);
                    cell.setCellStyle(styleField);

                    HSSFCell cell2 = rowField2.createCell(i);
                    cell2.setCellStyle(styleField);

                    if (i == 6){
                        CellRangeAddress cellRangeAddress = new CellRangeAddress(1, 1, i, i+1);
                        sheet.addMergedRegion(cellRangeAddress);
                        cell.setCellValue("合同工期");
                        cell2.setCellValue("开始");
                    }else if (i == 7){
                        cell2.setCellValue("终止");
                    }else if (i == 11){
                        CellRangeAddress cellRangeAddress = new CellRangeAddress(1, 1, i, i+1);
                        sheet.addMergedRegion(cellRangeAddress);
                        cell.setCellValue("合同评审");
                        cell2.setCellValue("是");
                    }else if(i == 13){
                        CellRangeAddress cellRangeAddress = new CellRangeAddress(1, 1, i, i+1);
                        sheet.addMergedRegion(cellRangeAddress);
                        cell.setCellValue("风险评估");
                        cell2.setCellValue("是");
                    }else  if (i == 12 ||i == 14){
                        cell2.setCellValue("否");
                    }else{
                        CellRangeAddress cellRangeAddress = new CellRangeAddress(1, 2, i, i);
                        sheet.addMergedRegion(cellRangeAddress);
                        cell.setCellValue(secondTitles[i]);
                    }
                }

                String[] beanProperty = { "contractId" , "contractNo","title","targetName","dateComment","authorizedRepresentative","durationStartdate","durationEnddate","executiveUnit","money","payment", "contractApproval1","contractApproval0", "riskAssessment1","riskAssessment0","remarks","contractType" };
                HSSFWorkbook workbook = ExcelUtil.exportExcelDatafirs(workbook1, contractListMap, beanProperty,3);
                ServletOutputStream out = response.getOutputStream();
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return contractLimsJson;
    }

    
    @ResponseBody
    @RequestMapping("/selectContracts")//是编辑回显
    public LimsJson selectContracts(HttpServletRequest request,@RequestParam("contractId") Integer contractId){
        return contractManageService.selectContracts(request,contractId);
    }
    @ResponseBody
    @RequestMapping("/selectContractZi")//查询所有子合同
    public LimsJson<Contract> selectContractZi(HttpServletRequest request, Integer page, Integer limit,Integer pageSize, Map map){
        return contractManageService.selectContractZi(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectContractZiBy")//模糊查询子合同  编号或标题
    public LimsJson<Contract> selectContractZiBy(HttpServletRequest request,@RequestParam("cha") String cha,Integer page,
                                               Integer limit,Integer pageSize, Map map){
        return contractManageService.selectContractZiBy(request,cha,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectContractMy")//查询我的合同
    public LimsJson<Contract> selectContractMy(HttpServletRequest request, Integer page, Integer limit,Integer pageSize, Map map){
        return contractManageService.selectContractMy(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectContractById")//查询合同
    public ToJson<Contract> selectContractById(HttpServletRequest request, Integer contractId){
        return contractManageService.selectContractById(request,contractId);
    }


    @ResponseBody
    @RequestMapping("/selectContractFlowById")//查询合同  流程
    public LimsJson<FlowRun> selectContractFlowById(HttpServletRequest request, Integer contractId){
        return contractManageService.selectContractFlowById(request,contractId);
    }
    @ResponseBody
    @RequestMapping("/selectContractTransportById")//查询合同  订单
    public LimsJson<ContractTransport> selectContractTransportById(HttpServletRequest request, Integer contractId){
        return contractManageService.selectContractTransportById(request,contractId);
    }
    @ResponseBody
    @RequestMapping("/selectContractRemindById")//查询合同  提醒
    public ToJson<ContractRemind> selectContractRemindById(HttpServletRequest request, Integer contractId){
        return contractManageService.selectContractRemindById(request,contractId);
    }
    @ResponseBody
    @RequestMapping("/selectContractProjectById")//查询合同  项目
    public LimsJson<ContractProject> selectContractProjectById(HttpServletRequest request, Integer contractId, String Flag){
        return contractManageService.selectContractProjectById(request,contractId,Flag);
    }
    @ResponseBody
    @RequestMapping("/selectContractZiById")//查询子合同  项目
    public LimsJson<Contract> selectContractZiById(HttpServletRequest request, Integer contractId){
        return contractManageService.selectContractZiById(request,contractId);
    }
    @ResponseBody
    @RequestMapping("/selectContractByNo")//新建合同时看编号是否重复
    public ToJson<Contract> selectContractByNo(HttpServletRequest request, String contractNo){
        return contractManageService.selectContractByNo(request,contractNo);
    }
    @ResponseBody
    @RequestMapping("/upContractUserId")//修改跟进人
    public ToJson<Contract> upContractUserId(HttpServletRequest request, Integer contractId,String userId){
        return contractManageService.upContractUserId(request,contractId,userId);
    }
    @ResponseBody
    @RequestMapping("/imports")//导入
    public ToJson<Contract> imports(HttpServletRequest request, MultipartFile file) throws IOException {
        return contractManageService.imports(request,file);
    }
    @ResponseBody
    @RequestMapping("/selectContractBy")//模糊查询合同  编号或标题
    public LimsJson<Contract> selectContractBy(HttpServletRequest request,@RequestParam("cha") String cha,Integer page,
                                               Integer limit,Integer pageSize, Map map){
        return contractManageService.selectContractBy(request,cha,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectContractByType")//根据类型查找
    public LimsJson<Contract> selectContractByType(HttpServletRequest request,@RequestParam("type") String type,Integer page,
                                               Integer limit,Integer pageSize, Map map){
        return contractManageService.selectContractByType(request,type,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectFlow")//查询所有流程
    public LimsJson<FlowRun> selectFlow(HttpServletRequest request, Integer page, Integer limit, Integer pageSize, Map map){
        return contractManageService.selectFlow(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectFlowBy")//查询  流程条件 标题
    public LimsJson<FlowRun> selectFlowBy(HttpServletRequest request, Integer page, Integer limit, Integer pageSize,
                                        @RequestParam("cha") String cha, Map map){
        return contractManageService.selectFlowBy(request,page,limit,pageSize,cha,map);
    }



    /*
    结算情况（项目）crud
     */
    @ResponseBody
    @RequestMapping("/insertProject")//增加项目
    public ToJson<ContractProject> insertProject(HttpServletRequest request, ContractProject contractProject){
        return contractManageService.insertProject(request,contractProject);
    }
    @ResponseBody
    @RequestMapping("/delProject")//删除项目
    public ToJson<ContractProject> delProject(HttpServletRequest request, @RequestParam("ids[]") Integer[] ids){
        return contractManageService.delProject(request,ids);
    }
    @ResponseBody
    @RequestMapping("/upProject")//更新项目
    public ToJson<ContractProject> upProject(HttpServletRequest request, ContractProject contractProject){
        return contractManageService.upProject(request,contractProject);
    }
    @ResponseBody
    @RequestMapping("/selectProjectAll")//查询所有项目
    public LimsJson<ContractProject> selectProjectAll(HttpServletRequest request, Integer page, Integer limit,Integer pageSize, Map map){
        return contractManageService.selectProjectAll(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/exportProject")//导出项目（结算情况）
    public LimsJson<ContractProject> exportProject(HttpServletRequest request,HttpServletResponse response,
                                                   @RequestParam("contractId") Integer contractId,String Flag){
        return contractManageService.exportProject(request,response,contractId,Flag);
    }

    @ResponseBody
    @RequestMapping("/exportContract")//导出合同（结算情况）
    public LimsJson<Contract> exportContract(HttpServletRequest request,HttpServletResponse response, Integer page, Integer limit,Integer pageSize, Map map,String contractType){
        return contractManageService.exportContract(request,response,page,limit,pageSize,map,contractType);
    }

    @ResponseBody
    @RequestMapping("/projectStatistics")//项目统计（结算情况）
    public LimsJson<ContractProject> projectStatistics(HttpServletRequest request,HttpServletResponse response,
                                                   @RequestParam("contractId") Integer contractId,String Flag){
        return contractManageService.projectStatistics(request,response,contractId,Flag);
    }
    @ResponseBody
    @RequestMapping("/selectProjectById")//一条项目
    public ToJson<ContractProject> selectProjectById(HttpServletRequest request,@RequestParam("conProjectId") Integer conProjectId){
        return contractManageService.selectProjectById(request,conProjectId);
    }



    /*
    订单（物流运输）crud
     */
    @ResponseBody
    @RequestMapping("/insertTransport")//增加物流运输
    public ToJson<ContractTransport> insertTransport(HttpServletRequest request, ContractTransport contractTransport){
        return contractManageService.insertTransport(request,contractTransport);
    }
    @ResponseBody
    @RequestMapping("/delTransport")//删除物流运输
    public ToJson<ContractTransport> delTransport(HttpServletRequest request, @RequestParam("ids[]") Integer[] ids){
        return contractManageService.delTransport(request,ids);
    }
    @ResponseBody
    @RequestMapping("/upTransport")//更新物流运输
    public ToJson<ContractTransport> upTransport(HttpServletRequest request, ContractTransport contractTransport){
        return contractManageService.upTransport(request,contractTransport);
    }
    @ResponseBody
    @RequestMapping("/selectTransportAll")//查询物流运输
    public LimsJson<ContractTransport> selectTransportAll(HttpServletRequest request, Integer page, Integer limit,Integer pageSize, Map map){
        return contractManageService.selectTransportAll(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectTransportById")//一条物流运输
    public ToJson<ContractTransport> selectTransportById(HttpServletRequest request,@RequestParam("transportId") Integer transportId){
        return contractManageService.selectTransportById(request,transportId);
    }



    /*
    相关流程crud
     */
    @ResponseBody
    @RequestMapping("/insertFlow")//增加流程
    public ToJson<ContractFlow> insertFlow(HttpServletRequest request, ContractFlow contractFlow){
        return contractManageService.insertFlow(request,contractFlow);
    }
    @ResponseBody
    @RequestMapping("/delFlow")//删除流程
    public ToJson<ContractFlow> delFlow(HttpServletRequest request, @RequestParam("ids[]") Integer[] ids){
        return contractManageService.delFlow(request,ids);
    }
    @ResponseBody
    @RequestMapping("/upFlow")//更新流程
    public ToJson<ContractFlow> upFlow(HttpServletRequest request, ContractFlow contractFlow){
        return contractManageService.upFlow(request,contractFlow);
    }
    @ResponseBody
    @RequestMapping("/selectFlowAll")//查询流程
    public LimsJson<ContractFlow> selectFlowAll(HttpServletRequest request, Integer page, Integer limit,Integer pageSize, Map map){
        return contractManageService.selectFlowAll(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectFlowById")//一条流程
    public ToJson<ContractFlow> selectFlowById(HttpServletRequest request,@RequestParam("conFlowId") Integer conFlowId){
        return contractManageService.selectFlowById(request,conFlowId);
    }
    /*
    提醒计划crud
     */
    @ResponseBody
    @RequestMapping("/insertRemind")//增加提醒
    public ToJson<ContractRemind> insertRemind(HttpServletRequest request, ContractRemind contractRemind){
        return contractManageService.insertRemind(request,contractRemind);
    }
    @ResponseBody
    @RequestMapping("/delRemind")//删除提醒
    public ToJson<ContractRemind> delRemind(HttpServletRequest request, @RequestParam("ids[]") Integer[] ids){
        return contractManageService.delRemind(request,ids);
    }
    @ResponseBody
    @RequestMapping("/upRemind")//更新提醒
    public ToJson<ContractRemind> upRemind(HttpServletRequest request, ContractRemind contractRemind){
        return contractManageService.upRemind(request,contractRemind);
    }
    @ResponseBody
    @RequestMapping("/selectRemindAll")//查询提醒
    public LimsJson<ContractRemind> selectRemindAll(HttpServletRequest request, Integer page, Integer limit,Integer pageSize, Map map){
        return contractManageService.selectRemindAll(request,page,limit,pageSize,map);
    }
    @ResponseBody
    @RequestMapping("/selectRemindById")//一条提醒
    public ToJson<ContractRemind> selectRemindById(HttpServletRequest request,@RequestParam("remindId") Integer remindId){
        return contractManageService.selectRemindById(request,remindId);
    }

    @ResponseBody
    @RequestMapping("/selectByMoney")
    public LimsJson selectByMoney (HttpServletRequest request, Integer page, Integer limit,Integer money,Integer moneys){
        return contractManageService.selectByMoney(request,page,limit,money,moneys);
    }

    @ResponseBody
    @RequestMapping("/selectBycontractType")
    public LimsJson selectBycontractType (HttpServletRequest request, Integer page, Integer limit,String contractType){
        return contractManageService.selectBycontractType(request,page,limit,contractType);
    }
}
